package com.zking.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zking.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

// @Component // 拦截器不需要加注解
// SpringMVC中配置：<interceptors><include-mapping xxx...>
public class MyInterceptor1 implements HandlerInterceptor {
    // Ctrl+O/I
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("~~~ 拦截请求：" + request.getRequestURI());
        if (request.getRequestURI().equals("/t2")) {
            // 判断是否登录
            if (request.getSession().getAttribute("user") != null) {
                return true;
            } else {
                // 需要响应：HTML页面，JSON对象
                // response.sendRedirect("/index");
                // response.setContentType("application/json;charset=utf-8");
                // response.getWriter().write(new ObjectMapper().writeValueAsString(new User(1001, "空", "拦截", 0.0)));
                response.sendRedirect("/json/index");
                return false;
            }
        }
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
